/**
 * 更新手机号
 * @param {Object} option
 */
export function updatePhone(code) {
	return new Promise((resolve, reject)=>{
		uni.$api.userUpdPhone({
			code: code
		}).then(data => {
			uni.$common.toastSuccess("已保存",()=>{
				let userInfo = wx.getStorageSync("userInfo")
				userInfo.phone = data
				wx.setStorageSync("userInfo",userInfo)
				resolve(data);
			})
		}).catch(error=>{
			reject(error)
		})
	})
}

/**
 * 更新用户某个值
 * @param {Object} field
 * @param {Object} value
 * @param {Object} event
 */
function updateInfo(field,value,event){
	uni.$api.userUpdInfo({
		id:uni.$user.getUserId(),
		[field]:value
	}).then(res=>{
		uni.$common.toastSuccess("已保存",()=>{
			let userInfo = uni.getStorageSync("userInfo")
			userInfo[field] = value
			uni.setStorageSync("userInfo",userInfo)
			
			if(uni.$common.isNotNull(event)){
				event()
			}
		})
	})
}

/**
 * 获取用户信息
 */
export function getUserInfo(){
	let userInfo = wx.getStorageSync("userInfo")
	if(uni.$common.isNull(userInfo)){
		userInfo = null
	}else if(userInfo == ''){
		userInfo = null
	}
	return userInfo
}

/**
 * 获取用户手机
 */
export function getUserPhone(){
	let userInfo = getUserInfo()
	if(userInfo == null){
		return ""
	}
	
	let phone = userInfo.phone
	if(uni.isNull(userInfo.phone)){
		phone = ''
	}
	return phone
}

/**
 * 获取用户id
 */
export function getUserId(){
	let userInfo = getUserInfo()
	if(userInfo == null){
		return ""
	}
	
	let userId = userInfo.phone
	if(uni.$common.isNull(userId)){
		userId = ''
	}
	return userId
}

let isGetUserCurLoc = -1
/**
 * 获取用户当前位置
 * @param {Object} option
 */
export function getUserCurLoc(event,isShuaxin) {
	if(typeof(isShuaxin) != "undefined" && isShuaxin!= null && isShuaxin == true){
		isGetUserCurLoc = -1
	}
	
	if(isGetUserCurLoc == 1){
		if(typeof(event) != "undefined" && event!= null){
			event(true)
		}
		return
	}
    uni.getLocation({
    	success: (res) => {
			uni.$api.userCurLocAdd({
				locLon:res.longitude,
				locLat:res.latitude
			}).then((res)=>{
				if(res.success){
					isGetUserCurLoc = 1
					event(true)
				}
			})
    	},
		fail: (res) => {
			isGetUserCurLoc = 2
			console.info("获取位置失败",res)
			if(res.errMsg == "getLocation:fail auth deny"){
				checkAuth("scope.userLocation").then((res)=>{
					getUserCurLoc(event)
				}).catch(()=>{
					event(false)
					uni.showModal({
						title:"温馨提示",
						content:"已拒绝授权，部分功能将无法使用",
						showCancel:false
					})
				})
			}else if(res.errMsg == "getLocation:fail Failed to fetch"){
				uni.showModal({
					title:"温馨提示",
					content:"请打开定位，稍后重试",
					showCancel:false,
				})
			}else{
				uni.showModal({
					title:"温馨提示",
					content:"位置获取失败，请稍后重试!",
					showCancel:false,
				})
			}
		}
    })
}

export function checkAuth(scope){
    return new Promise((resolve,reject)=>{
        uni.getSetting({
            success(res) {
                console.log(res.authSetting)
                if (!res.authSetting[scope]) {
                    uni.authorize({
                        scope,
                        success() {
                            resolve()
                        },
                        fail() {
                            uni.hideLoading();
                            uni.showModal({
                                title: '温馨提示',
                                content: '您已拒绝授权，是否去设置打开？',
                                confirmText: "确认",
                                cancelText: "取消",
                                success: function(res) {
                                    // console.log(res);
                                    if (res.confirm) {
                                        uni.hideLoading();
                                        uni.openSetting({
                                            success: (res) => {
                                                if(res.authSetting[scope] === true){
													resolve()
												}else{
													reject({errMsg:'用户拒绝授权'})
												}
                                            }
                                        });
                                    } else {
                                        reject({errMsg:'用户拒绝授权'})
                                    }
                                },
                                fail(res) {
                                    reject(res)
                                }
                            });

                        }
                    })
                } else {
                    resolve()
                }
            },
            fail(res) {
                reject(res)
            }
        })
    })
}

export default {
	updatePhone:updatePhone,
	updateInfo:updateInfo,
	getUserInfo:getUserInfo,
	getUserPhone:getUserPhone,
	getUserId:getUserId,
	getUserCurLoc:getUserCurLoc,
}